import axios from "axios";
import {useUserStore} from "@/stores/user";
import {computed} from "vue";

const serverConfig = {
    // 开发环境
    development: {
        baseURL: 'http://localhost:8080/api/'
    },
    // 线上环境
    production: {
        baseURL: 'https://g.processor.org.cn/api/'
    }
}

const request = axios.create({baseURL: serverConfig[process.env.NODE_ENV].baseURL})
request.interceptors.request.use(request => {
    const store = useUserStore()
    request.headers.access_token = computed(() => store.token).value
    return request
})

request.interceptors.response.use(
    resp => {
        if(resp.status === 200) {
            const res = resp.data
            if (res.ret === 10000) {
                // access_token 已刷新，需要拿到服务器返回的最新的 access_token 进行请求重发
                const store = useUserStore()
                store.$patch({token: res.data})

                resp.headers.access_token = res.data
                return this.request()
            } else if (res.ret === 10001) {
                // access_token 失效
                const store = useUserStore()
                store.$reset()
            }

            return resp.data
        }

        return Promise.reject(resp)
    }
)

export default request
